package imgshare.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
//import org.thymeleaf.TemplateEngine;
//import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class MailUtil {

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;

//    @Autowired
//    private TemplateEngine templateEngine;

    public void sendSimpleMail(String to,String subject,String content) {

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        simpleMailMessage.setFrom(from);

        mailSender.send(simpleMailMessage);
    }

    public void sendMailWithAttachment(String to,String subject,String text)
            throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text);
        ClassPathResource resource = new ClassPathResource("/static/img/girl.jpg");
        helper.addAttachment("girl.jpg",resource);
        mailSender.send(mimeMessage);

    }

//    public void sendHTMLMail(String to,String subject) throws MessagingException {
//
//        Context context = new Context();
//        context.setVariable("id","06");
//        context.setVariable("name","hauss");
//        String text = templateEngine.process("email.html", context);
//
//        MimeMessage message = mailSender.createMimeMessage();
//        MimeMessageHelper helper = new MimeMessageHelper(message,true);
//
//        //抄送一份给自己，应对被当做垃圾邮件
////        message.addRecipients(Message.RecipientType.CC,from);
//
//        helper.setFrom(from);
//        helper.setTo(to);
//        helper.setSubject(subject);
//        helper.setText(text,true);  //true：useHTML
//
//        mailSender.send(message);
//
//    }
}
